#include "at32f421_board.h"
#include "at32f421_clock.h"

#include "drv_lcd.h"
#include "drv_adc.h"
#include "drv_tmr.h"
#include "drv_key.h"
#include "drv_vbus_sw.h"

#include "fui.h"
#include "menu_handle.h"

#include "lcd.h"
#include "pic.h"

void swj_dp_config(void)
{
    // AT32F421K8U7 DON'T NEED CONFIG
    crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE);
}

int main(void)
{
    system_clock_config();
    nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
  
    vbus_sw_gpio_init();
    swj_dp_config();

    delay_init();
    LCD_Init();
    
    LCD_Fill(0, 0, LCD_W, LCD_H, BLACK);
    LCD_BLK_Set();
    
    usb_adc_tmr_config();
    usb_adc_gpio_init();
    
    // 零点电流校准
    key_gpio_init();
    if(!KEY1_READ())
    {
        delay_ms(10);
        if(!KEY1_READ())
        {
            VBUS1_ON();
            VBUS2_ON();
            VBUS3_ON();
            VBUS4_ON();
            
            LCD_ShowString(0, 0, (uint8_t*)"Wait USB Conn...", BLACK, RED, 20,0);
            delay_ms(5000);
            LCD_ShowString(0, 0, (uint8_t*)"Calibrate, Wait...", BLACK, RED, 20,0);
            usb_adc_calibrate_offsets();
        }
    }
    usb_adc_load_calibrate_data();
    usb_adc_dma_config();
    usb_adc_config();
    tick_tmr_config();
    
    // BootLogo
    LCD_ShowPicture(80, 20, 80, 80, gImage_pic);
    display_about_sw();
    delay_sec(1);
    LCD_Fill(0, 0, LCD_W, LCD_H, BLACK);
    display_about_sw();
  
    // VBUS ON
    VBUS1_ON();
    VBUS2_ON();
    VBUS3_ON();
    VBUS4_ON();
    
    key_scan_init();

    while(1)
    {
        usb_adc_calc_state();
        menu_key_handle();
        task_display_handle();
    }
}
